package cn.exrick.xboot.common.exception;


import cn.exrick.xboot.common.utils.ResultUtil;

import cn.exrick.xboot.common.vo.Result;
import lombok.extern.slf4j.Slf4j;

import org.springframework.http.HttpStatus;

import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author Exrickx
 */
@Slf4j
@RestControllerAdvice
public class RestCtrlExceptionHandler {

    @ExceptionHandler(XbootException.class)
    @ResponseStatus(value = HttpStatus.OK)
    public Result<Object> handleXCloudException(XbootException e) {

        String errorMsg="Xboot exception";
        if (e!=null){
            errorMsg=e.getMsg();
            log.error(e.toString());
        }
        return new ResultUtil<>().setErrorMsg(500, errorMsg);
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.OK)
    public Result<Object> handleException(Exception e) {

        String errorMsg="Exception";
        if (e!=null){
            errorMsg=e.getMessage();
            log.error(e.toString());
        }
        return new ResultUtil<>().setErrorMsg(500, errorMsg);
    }
    @ExceptionHandler(ServiceException.class)
    @ResponseStatus(value = HttpStatus.OK)
    public Result<Object> handleException(ServiceException e) {
        String errorMsg="Exception";
        if (e!=null){
            errorMsg=e.getMessage();
            log.error(e.toString());
        }
        return new ResultUtil<>().setErrorMsg(e.getCode(), errorMsg);
    }
    @ExceptionHandler(BindException.class)
    @ResponseStatus(value = HttpStatus.OK)
        public Result<Object> handleException(BindException  e) {
        BindingResult bindingResult = e.getBindingResult();
        StringBuffer errorMsg=new StringBuffer(bindingResult.getFieldErrors().size()*16);
        if (e!=null){
            for(int i=0;i<bindingResult.getFieldErrors().size();i++){
                if(i>0){
                    errorMsg.append(",");
                }
                FieldError fieldError = bindingResult.getFieldErrors().get(i);
                errorMsg.append(fieldError.getField());
                errorMsg.append(":");
                errorMsg.append(fieldError.getDefaultMessage());
            }
            log.error(e.toString());
        }
        return new ResultUtil<>().setErrorMsg(500, errorMsg.toString());
    }





}
